<template>
  <div style="background-color: white;width:calc(100% - 10px);height: 100%;padding: 20px 0 20px 10px;">
    <div @click="showProduct = true" class="open-bt">产品列表</div>
    <div class="list-title">
      <div>
        <div>名称</div>
        <div>售价</div>
        <div>数量</div>
        <!-- <div>单位</div> -->
        <div>小计</div>
        <div>操作</div>
      </div>
    </div>
    <div class="list list-title" style="height:auto;max-height:calc(70vh);">
      <div v-for="(item,i) in selectList" :key="i">
        <div>{{ item.productName }}</div>
        <div @click="editKey = 'price' + item.productId">
          <van-field
            v-if="editKey == ('price'+item.productId)"
            v-model="item.price"
            @blur="modifyPrice($event, i, 'price')"
            type="number" />
          <div v-else>{{ item.price }}</div>
        </div>
        <div @click="editKey = 'num' + item.productId">
          <van-field
            v-if="editKey == ('num'+item.productId)"
            v-model="item.quantity"
            @blur="modifyPrice($event, i, 'num')"
            type="number" />
          <div v-else>{{ item.quantity }}</div>
        </div>
        <!-- <div>{{ item.unit }}</div> -->
        <div>{{ item.subtotal }}</div>
        <div @click="deleteProduct(i)" style="color:red;">删除</div>
      </div>
    </div>


    <div class="count-view">
      <div class="title">价格计算</div>
      <div class="price-class">
        <div>
          <span>项目总计</span>
          <div class="price">{{totalPrice}}</div>
        </div>
        <div>
          <span>税金</span>
          <div class="price">{{ taxes }}</div>
        </div>
      </div>
      <div class="price-class">
        <div>
          <span>现金优惠</span>
          <a-input-number
            v-model="discounts"
            style="width:100%"
            @blur="blurDiscounts"
            placeholder="请输入现金优惠"></a-input-number>
        </div>
        <div>
          <span>订单总价</span>
          <div class="price">{{ total }}</div>
        </div>
      </div>
      <a-row style="margin: 20px 0;">
        <a-col :span="24" style="text-align: right;">
          <a-button type="primary" @click="computePrice">计算订单总价</a-button>
          <a-button type="primary" v-has="'customer:designAdd'" @click="add" :landing="landing" style="margin-left: 8px">保存方案</a-button>
        </a-col>
      </a-row>
    </div>


    <van-popup v-model="showProduct" position="bottom" :style="{ height: 'auto' }" closeable >
      <van-field
      style="margin-top:50px;"
          v-model="searchText"
          clearable
          label="搜索"
          placeholder="请输入搜索内容"
          @input="searchProduct"/>
      <div class="list-title">
        <div>
          <div>名称</div>
          <div>售价</div>
          <div>数量</div>
          <!-- <div>单位</div> -->
          <div>小计</div>
          <div>操作</div>
        </div>
      </div>
      <div class="list list-title" style="height:auto;max-height:calc(70vh);min-height:40px;">
        <div v-for="(item,i) in searchList" :key="i">
          <div>{{ item.productName }}</div>
          <div>{{ item.price }}</div>
          <div>{{ item.quantity }}</div>
          <!-- <div>{{ item.unit }}</div> -->
          <div>{{ item.subtotal }}</div>
          <div @click="joinProduct(i)" style="color:rgb(47, 224, 47);">加入</div>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script>
  import difference from 'lodash/difference';
  import { getAction, postAction, deleteAction } from '@/api/manage'
  import {
    Toast
  } from 'vant';
  export default {
    name: 'designService',
    components: {},
    props: {
      customerId: {
        required: true,
        default: 0
      },
    },
    data() {
      return {
        selectList:[],//已选
        productList:[],//未选
        searchList: [],//搜索列表
        showProduct:false,
        totalPrice: 0,//项目总价
        taxes: 0,
        discounts: 0,
        total: 0,
        editKey: false,
        searchText: '',
        landing: false,
        dataSource: [],
        url: {
          list: '/ghProductManage/queryList',
          designServiceList: '/ghCustomerDesignService/list',
          delete: '/ghCustomerDesignService/delete',
          deleteBatch: '/ghCustomerFileInfo/deleteBatch',
          exportXlsUrl: '/ghCustomerFileInfo/exportXls',
          importExcelUrl: '/ghCustomerFileInfo/importExcel',
          deleteBatch2: '/ghCustomerFileInfo/deleteBatch',
          fileTrendsList: '/ghCustomerFileTrendsRecord/list',
          add: "/ghCustomerDesignService/add",
          getParent: "/ghProductType/getProductParent"
        },
      }
    },
    created() {
      this.loadProductData();
    },
    methods: {
      //删除
      deleteProduct(i){
        this.searchList.push(this.selectList[i])
        deleteAction(this.url.delete, {id:this.selectList[i].key}).then((res) => {
          if (res.success) {
            this.$message.success(res.message)
          } else {
            this.$message.warning(res.message);
          }
        }).finally(() => {

        })
        this.countTotalPrice()
        this.selectList.splice(i,1)
      },
      //加入
      joinProduct(i){
        this.selectList.push(this.searchList[i])
        let obj = this.searchList.splice(i,1)
        for(let n=0;n<this.productList.length;n++){
          if(this.productList[n].productId==obj[0].productId){
            this.productList.splice(n, 1)
          }
        }
        this.countTotalPrice()
      },
      //计算小计
      modifyPrice(e, i, status){
        console.log(e.target._value)
        if(e.target._value == '' || e.target._value == '0' ){
          Toast.fail('数值不能为空');
          if(status === 'price'){
            this.selectList[i].price = 1
          }else{
            this.selectList[i].quantity = 1
          }
        }
        this.editKey = false
        let obj = this.selectList[i]
        this.selectList[i].subtotal = obj.price * obj.quantity
        this.countTotalPrice()
      },
      //计算总价
      countTotalPrice(){
        let price = 0
        console.log(this.selectList)
        for(let i=0;i<this.selectList.length;i++){
          price += this.selectList[i].subtotal
        }
        this.totalPrice = price
        this.taxes = (price * 0.06).toFixed(2);
      },
      //计算订单总价
      computePrice(){
        this.countTotalPrice()
        if(this.discounts*1 > this.totalPrice*1){
          this.discounts = 0
          Toast.fail('优惠不能大于总计');
        }else{
          function cfloat(number){
            let num = number*1
            return parseFloat(num.toFixed(2))
          }
          this.total = cfloat(this.totalPrice) + cfloat(this.taxes) - cfloat(this.discounts)


        }
      },
      //搜索
      searchProduct(){
        this.searchList = this.productList.filter(item=>{
          return item.productName.includes(this.searchText)
        })
      },
      blurDiscounts(){
        if(isNaN(this.discounts)) return
        this.discounts = (this.discounts*1).toFixed(2)
      },
      //获取全部产品
      loadProductData(){
        this.dataSource = [];
        getAction(this.url.list).then((res) => {
          if (res.success) {
            let list = res.result.records || res.result
            if(list) {
              list.forEach(item => {
                this.dataSource.push({
                  key: item.id.toString(),
                  title: item.productName,
                  productId: item.id,
                  customerId: this.customerId,
                  productName: item.productName,
                  unit: item.unit,
                  productPrice: item.productPrice,
                  price: item.productPrice,
                  quantity: 1,
                  subtotal: 1 * item.productPrice
                })
              })
              this.initData();
            }
          }else{
            this.$message.warning(res.message)
          }
        })
      },
      //获取已选
      initData() {
        getAction(this.url.designServiceList, {
          customerId: this.customerId
        }).then(res => {
          if(res.success) {
            let data = res.result.records || res.result;
            data.forEach(item => {
              this.selectList.push({
                key: item.id.toString(),
                title: item.productName,
                productId: item.productId,
                customerId: this.customerId,
                productName: item.productName,
                unit: item.unit,
                productPrice: item.price,
                price: item.price,
                quantity: item.quantity,
                subtotal: item.quantity * item.price
              })
            })

            let idList = []
            for(let i=0;i<data.length;i++){
              idList.push(data[i].productId)
            }
            //未选产品数据
            this.productList = this.dataSource.filter(item=>{
              return !idList.includes(item.productId)
            })
            this.searchList = this.productList

            let totalPrice = 0;
            data.forEach(i => {
              totalPrice += i.quantity * i.price;
            })

            this.totalPrice = parseFloat(totalPrice).toFixed(2);;
            this.taxes = (totalPrice * 0.06).toFixed(2)
          }
        });
      },
      add() {
        this.landing = true;
        if(this.selectList.length == 0) {
          this.$message.warning("方案无产品，无需保存！");
          return;
        }
        let params = {
          designServiceList: this.selectList
        }
        postAction(this.url.add, params).then((res) => {
          if (res.success) {
            this.$message.success(res.message)
          } else {
            this.$message.warning(res.message);
          }
        }).finally(() => {
          this.landing = false;
        })
      },
    }
  }
</script>
<style scoped lang="less">
  @import '~@assets/less/common.less';
  .open-bt{
    width:100%;
    height:40px;
    border-radius: 10px;
    border: 1px solid #ddd;
    line-height: 40px;
    text-align: center;
  }
  .count-view{
    width: 100%;
    height: auto;
    border: 1px solid rgb(217, 217, 217);
    margin-top: 30px;
    padding: 0 10px;
    .title{
      line-height: 50px;
      font-size: 15px;
      border-bottom: 1px solid rgba(217, 217, 217, 0.5);
      font-weight: bold;
    }
    .price-class{
      display: flex;
      &>div{
        width: 50%;
        span{
          line-height: 30px;
        }
        .price{
          color: #f40;
          height:20px;
          line-height: 20px;
          margin-bottom: 20px;
        }
        .ant-input-number{
          width: 10em !important;
        }
      }
    }
  }

  .list-title{
    width: 100%;
    height:40px;
    &>div{
      display: flex;
      align-items: center;
      justify-content: space-between;
      min-height: 40px;
      text-align: center;
      &>div:nth-child(1){
        width: 30%;
      }
      &>div:nth-child(2){
        width: 20%;
      }
      &>div:nth-child(3){
        width: 20%;
      }
      &>div:nth-child(4){
        width: 20%;
      }
      &>div:nth-child(5){
        width: 10%;
      }
    }
  }
  .list{
    height:calc(100vh - 280px);
    overflow-y:scroll;
  }
  ::-webkit-scrollbar {
    display: none;
  }
  .editable-row-operations a {
    margin-right: 8px;
  }
</style>